package cn.edu.sdyu.ie.crs.service.impl;

import cn.edu.sdyu.ie.crs.domain.User;
import cn.edu.sdyu.ie.crs.repository.UserRepository;
import cn.edu.sdyu.ie.crs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public Page<User> findByPage(Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize, Sort.by(Sort.Direction.DESC,"id"));
        return userRepository.findAll(pageable);
    }

    @Override
    public User findUserById(Integer id) {
        Optional<User> optional = userRepository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        } else {
            log.warn("指定用户信息[ID:{}]不存在", id);
            return null;
        }

        // return userRepository.findById(id).orElse(null);
    }

    @Override
    public void saveUser(User user) {
        if(user.getId() == null) {
            user.setCreateTime(new Date());
        }
        userRepository.save(user);
    }
    @Override
    public void deleteUserById(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public Long countUser() { return userRepository.count(); }

    @Override
    public Long countUserByUserStatus(Integer userStatus) {
        User user = new User();
        user.setUserStatus(userStatus);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("userStatus", ExampleMatcher.GenericPropertyMatchers.exact());
        Example<User> example = Example.of(user, matcher);
        return userRepository.count(example);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(String.format("用户[%s]不存在！", username));
        }
        return user;
    }
}
